package com.gzx.plugin.tjzy.modular.sms.api.strategy.yz.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.gzx.plugin.tjzy.modular.founds.service.GzxFoundsFlowService;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.SMSStrategy;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.common.dto.CommonSmsSendReqDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.common.dto.CommonSmsSendRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.yz.dto.SMSYZReceiptRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.yz.dto.SMSYZReplyRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.yz.dto.SMSYZSendRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.template.SmsTemplateMethod;
import com.gzx.plugin.tjzy.modular.sms.batch.consts.SMSYZConstant;
import com.gzx.plugin.tjzy.modular.sms.batch.enums.GzxSmsSendStatusEnum;
import com.gzx.plugin.tjzy.modular.sms.batch.service.GzxSmsDbService;
import com.gzx.plugin.tjzy.modular.sms.receipt.consts.GzxSendStatusMappingConstant;
import com.gzx.plugin.tjzy.modular.sms.receipt.entity.GzxSmsReceipt;
import com.gzx.plugin.tjzy.modular.sms.receipt.service.GzxSmsReceiptService;
import com.gzx.plugin.tjzy.modular.sms.record.service.GzxSmsRecordService;
import com.gzx.plugin.tjzy.modular.sms.reply.entity.GzxSmsReply;
import com.gzx.plugin.tjzy.modular.sms.reply.service.GzxSmsReplyService;
import com.gzx.plugin.tjzy.modular.supplier.consts.GzxSupplierConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.util.CommonDateUtil;
import vip.xiaonuo.common.util.CommonHttpUtil;

import java.util.*;

/**
 * @author zjt
 * @description
 * @date 2025/7/21 15:28
 */
@Slf4j
@Service
public class SMSYZStrategyImpl extends SmsTemplateMethod implements SMSStrategy {

	@Value("${sms.yz.url}")
	private String url;

	@Value("${sms.yz.account}")
	private String account;

	@Value("${sms.yz.password}")
	private String password;

	@Value("${sms.yz.extno}")
	private String extno;

	@Value("${sms.yz.size}")
	private int size;

	private static final String ACTION = "action";

	private static final String ACCOUNT = "account";

	private static final String PASSWORD = "password";

	public SMSYZStrategyImpl(GzxSmsDbService smsDbService, GzxSmsRecordService smsRecordService,
			GzxSmsReceiptService smsReceiptService, GzxFoundsFlowService foundsFlowService,
			GzxSmsReplyService smsReplyService) {
		super(smsDbService, smsRecordService, smsReceiptService, foundsFlowService, smsReplyService);
	}

	/**
	 * 获取当前供应商
	 *
	 * @return
	 */
	@Override
	public String getCurrentSupplierCode() {
		return GzxSupplierConstant.YZ;
	}

	/**
	 * 获取短信签名
	 *
	 * @param city
	 * @return
	 */
	@Override
	protected String getSignName(String city) {
		if ("天津".equals(city)) {
			return "【天津普惠金融调解中心】";
		}
		if ("盐城".equals(city)) {
			return "【盐城市盐南高新区金和金融调解中心】";
		}
		return "";
	}

	/**
	 * 开始发送短信
	 *
	 * @param commonSmsSendReqDtoList 发送短信的集合
	 * @return
	 */
	@Override
	protected List<CommonSmsSendRespDto> startSend(List<CommonSmsSendReqDto> commonSmsSendReqDtoList) {
		Map<String, String> smsParam = new HashMap<>();
		Map<String, String> phoneMap = new HashMap<>();
		for (CommonSmsSendReqDto commonSmsSendReqDto : commonSmsSendReqDtoList) {
			smsParam.put(commonSmsSendReqDto.getPhone(),
					modifySmsSignature(commonSmsSendReqDto.getSignCity(), commonSmsSendReqDto.getMessage()));
			phoneMap.put(commonSmsSendReqDto.getPhone(), commonSmsSendReqDto.getSupplierOrder());
		}
		Map<String, Object> reqBody = new HashMap<>();
		reqBody.put(ACTION, SMSYZConstant.ONE_ONE);
		reqBody.put(ACCOUNT, account);
		reqBody.put(PASSWORD, password);
		reqBody.put("extno", extno);
		reqBody.put("mobileContentKvp", smsParam);
		try {
			String respBody = CommonHttpUtil.post(url, null, JSON.toJSONString(reqBody), "越众短信发送");
			SMSYZSendRespDto smsyzSendRespDto = JSON.parseObject(respBody, SMSYZSendRespDto.class);
			if (smsyzSendRespDto != null && smsyzSendRespDto.getStatus() == 0
					&& CollectionUtil.isNotEmpty(smsyzSendRespDto.getList())) {
				List<CommonSmsSendRespDto> commonSmsSendRespDtoList = new ArrayList<>();
				for (SMSYZSendRespDto.PhoneResult phoneResult : smsyzSendRespDto.getList()) {
					String supplierOrder = phoneMap.get(phoneResult.getMobile());
					Integer result = 0;
					if ((supplierOrder.endsWith(GzxSupplierConstant.YZ) && phoneResult.getResult() != 0)) {
						result = GzxSmsSendStatusEnum.FINAL_FAIL.getCode();
						log.warn("mobile:{} send fail", phoneResult.getMobile());
					}
					commonSmsSendRespDtoList
							.add(new CommonSmsSendRespDto(phoneResult.getMobile(), phoneResult.getMid(), result));

				}
				return commonSmsSendRespDtoList;
			} else {
				log.warn("调用越众短信发送接口 status:", smsyzSendRespDto.getStatus());
			}
			return defaultResp(commonSmsSendReqDtoList, GzxSmsSendStatusEnum.FAIL.getCode(), GzxSupplierConstant.YZ);
		} catch (Exception e) {
			log.error("调用越众短信发送接口出现异常", e);
			return defaultResp(commonSmsSendReqDtoList, GzxSmsSendStatusEnum.FAIL.getCode(), GzxSupplierConstant.YZ);
		}
	}

	/**
	 * 同步短信回执
	 *
	 * @return
	 */
	@Override
	protected List<GzxSmsReceipt> startSyncReceipt() {
		Map<String, Object> reqBody = new HashMap<>();
		reqBody.put(ACTION, SMSYZConstant.RECEIPT);
		reqBody.put(ACCOUNT, account);
		reqBody.put(PASSWORD, password);
		reqBody.put("size", size);
		try {
			String respBody = CommonHttpUtil.post(url, null, JSON.toJSONString(reqBody), "越众短信状态查询");
			SMSYZReceiptRespDto smsyzReceiptRespDto = JSON.parseObject(respBody, SMSYZReceiptRespDto.class);
			List<GzxSmsReceipt> smsReceiptList = new ArrayList<>();
			if (smsyzReceiptRespDto != null && smsyzReceiptRespDto.getStatus() == 0
					&& CollectionUtil.isNotEmpty(smsyzReceiptRespDto.getList())) {
				String currentDate = CommonDateUtil.getCurrentTimeStr();
				for (SMSYZReceiptRespDto.YZReceiptDetail yzReceiptDetail : smsyzReceiptRespDto.getList()) {
					GzxSmsReceipt smsReceipt = new GzxSmsReceipt();
					smsReceipt.setSupplierCode(GzxSupplierConstant.YZ);
					smsReceipt.setFlagType(yzReceiptDetail.getFlag());
					smsReceipt.setPhone(yzReceiptDetail.getMobile());
					smsReceipt.setMsgId(yzReceiptDetail.getMid());
					smsReceipt.setSendTime(yzReceiptDetail.getTime());
					smsReceipt.setResultCode(yzReceiptDetail.getStat());
					smsReceipt.setMappingStatus(GzxSupplierConstant.YZ_SUCCESS.equals(yzReceiptDetail.getStat())
							? GzxSendStatusMappingConstant.SUCCESS
							: GzxSendStatusMappingConstant.FAIL);
					smsReceipt.setAllDetail(JSON.toJSONString(yzReceiptDetail));
					smsReceipt.setCreateTime(currentDate);
					smsReceiptList.add(smsReceipt);
				}
			}
			return smsReceiptList;
		} catch (Exception e) {
			log.error("调用越众短信状态查询接口出现异常", e);
			return Collections.emptyList();
		}
	}

	/**
	 * 开始同步短信回复
	 *
	 * @return
	 */
	@Override
	protected List<GzxSmsReply> startSyncReply() {
		Map<String, Object> reqBody = new HashMap<>();
		reqBody.put(ACTION, SMSYZConstant.REPLY);
		reqBody.put(ACCOUNT, account);
		reqBody.put(PASSWORD, password);
		try {
			String respBody = CommonHttpUtil.post(url, null, JSON.toJSONString(reqBody), "越众短信回复查询");
			SMSYZReplyRespDto smsyzReplyRespDto = JSON.parseObject(respBody, SMSYZReplyRespDto.class);
			List<GzxSmsReply> smsReplyList = new ArrayList<>();
			if (smsyzReplyRespDto != null && smsyzReplyRespDto.getStatus() == 0
					&& CollectionUtil.isNotEmpty(smsyzReplyRespDto.getList())) {
				String currentDate = CommonDateUtil.getCurrentTimeStr();
				for (SMSYZReplyRespDto.YZReplyDetail yzReplyDetail : smsyzReplyRespDto.getList()) {
					yzReplyDetail.setContent(
							StringUtils.deleteWhitespace(yzReplyDetail.getContent()).replaceAll("[\\x00-\\x1F]", ""));
					GzxSmsReply smsReply = new GzxSmsReply();
					smsReply.setSupplierCode(GzxSupplierConstant.YZ);
					smsReply.setMsgId(yzReplyDetail.getMid());
					smsReply.setPhone(yzReplyDetail.getMobile());
					smsReply.setReplyContent(yzReplyDetail.getContent());
					smsReply.setReplyTime(yzReplyDetail.getTime());
					smsReply.setReplyDetail(JSON.toJSONString(yzReplyDetail));
					smsReply.setCreateTime(currentDate);
					smsReplyList.add(smsReply);
				}
			}
			return smsReplyList;
		} catch (Exception e) {
			log.error("调用越众短信回复查询接口出现异常", e);
			return Collections.emptyList();
		}
	}

	@Override
	protected boolean isSuccess(String resultCode) {
		return GzxSupplierConstant.YZ_SUCCESS.equals(resultCode);
	}

	/**
	 * 是否需要根据短信ID分组
	 *
	 * @return
	 */
	@Override
	protected boolean isMsgIdGroup() {
		return false;
	}

}
